package com.minimalist.common.config.mybatis;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.minimalist.common.config.mybatis.bo.BaseEntity;
import com.minimalist.common.utils.CommonConstant;
import com.mybatisflex.annotation.InsertListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Mybatis-Flex 插入时字段自动填充。注：xml中和Db+Row插入不会生效需要手动set
 *
 * @author 11987
 */
@Component
public class InsertFullColumnHandler implements InsertListener{
    private static final Logger log = LoggerFactory.getLogger(InsertFullColumnHandler.class);


    @Override
    public void onInsert(Object entity){
        BaseEntity t = (BaseEntity) entity;
        if (t.getUpdateId() != null && t.getCreateId() != null){
            return;
        }
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if (ObjectUtil.isNotNull(tokenInfo) && ObjectUtil.isNotNull(tokenInfo.getLoginId())){
            long userId = Long.parseLong(tokenInfo.getLoginId().toString());
            t.setCreateId(userId);
            t.setUpdateId(userId);
        } else{
            t.setCreateId((long) CommonConstant.ZERO);
            t.setUpdateId((long) CommonConstant.ZERO);
        }

    }

}

